/* Copyright (c) 2015,2016 Lucky Byte, Inc.
 */
package com.lucky_byte.pay.jar;

import java.util.ArrayList;
import java.util.List;

import freemarker.template.TemplateCollectionModel;
import freemarker.template.TemplateHashModelEx;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import freemarker.template.WrappingTemplateModel;

/**
 * 封装 Jdbc Record 对象
 */
public class FMJdbcRecord extends WrappingTemplateModel
	implements TemplateHashModelEx
{
	private JdbcRecord record;

	@SuppressWarnings("deprecation")
	public FMJdbcRecord(JdbcRecord record) {
		this.record = record;
	}

	@Override
	public TemplateModel get(String key) throws TemplateModelException {
		if (record == null) {
			return null;
		}
		return wrap(record.getField(key));
	}

	@Override
	public boolean isEmpty() throws TemplateModelException {
		if (record == null) {
			return true;
		}
		return record.FieldSet().size() == 0;
	}

	@Override
	public int size() throws TemplateModelException {
		if (record == null) {
			return 0;
		}
		return record.FieldSet().size();
	}

	@Override
	public TemplateCollectionModel keys() throws TemplateModelException {
		if (record == null) {
			return null;
		}
		return (TemplateCollectionModel) wrap(record.FieldSet());
	}

	@Override
	public TemplateCollectionModel values() throws TemplateModelException {
		if (record == null) {
			return null;
		}
		List<Object> values = new ArrayList<>();
		for (String key : record.FieldSet()) {
			values.add(record.getField(key));
		}
		return (TemplateCollectionModel) wrap(values);
	}

}
